// pages/UserStatistics/PersonnelDetails/PersonnelDetails.js
const controllers = require('../../pages/controllers/controllerIndex.js').controller;
import * as echarts from '../ec-canvas/echarts';
const app = getApp();
// echarts初始化
let chart
let isInitEC=false

function initChart(canvas, width, height) {
  chart = echarts.init(canvas, null, {
    width: width,
    height: height,
    devicePixelRatio: 2 // 像素比
  });
  canvas.setChart(chart);
  isInitEC=true
  return chart;
}


Page({

  /**
   * 页面的初始数据
   */
  data: {
    tabList: ["线上订单", "线下订单", "线下预约", "云服务订单", "会员卡提成", "提成记录", "提现记录"],
    currentIndex: 0,
    startTime: "",
    endTime: "",
    status: 0,
    accountId: '',
    pageNumber: 1,
    pageSize: 1,
    lastPage: false,
    getMore: false,
    orderList: [],
    ec: {
      onInit: initChart
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      shopAccountId: options.id,
    })
    this.staffDetail()
    this.getOrderList()
  },
  // 员工信息
  staffDetail() {
    let date = new Date();

    let year = date.getFullYear()
    let month = date.getMonth() + 1
    let day = date.getDate()
    controllers.staffDetail({
      sessionId: wx.getStorageSync('token'),
      shopId: wx.getStorageSync('shopId'),
      shopAccountId: this.data.shopAccountId,
      //  head:options.head
    }).then(res => {
      res.data.lowOrderMoney = res.data.lowOrderMoney ? res.data.lowOrderMoney.toFixed(2) : '00.00'
      res.data.upOrderMoney = res.data.upOrderMoney ? res.data.upOrderMoney.toFixed(2) : '00.00'
      res.data.totleWithdrawal = (res.data.waitMoney || 0) + (res.data.withdrawMoney || 0)
      res.data.totleWithdrawal = res.data.totleWithdrawal ? res.data.totleWithdrawal.toFixed(2) : '00.00'
      res.data.withdrawalMoney = res.data.withdrawalMoney ? res.data.withdrawalMoney.toFixed(2) : '00.00'
      res.data.waitMoney = res.data.waitMoney ? res.data.waitMoney.toFixed(2) : '00.00'
      this.setData({
        nowDate: year + '-' + month + '-' + day,
        userInfo: res.data,
        nowMonth: month,
      });
      // echarts初始化完成后赋值
      
      setTimeout(()=>{
        this.initChartOption(res.data.waitMoney, res.data.withdrawalMoney)
      },1200)

    })
  },
  initChartOption(value1, value2) {
    chart.setOption({
      color: ["#F56666", "#66C1F5"],
      legend: {
        show:false,
      },
      series: [{
        type: 'pie',
        radius: ['54%', '84%'],
        center: ["50%", "38%"],
        avoidLabelOverlap: false,
        itemStyle: {
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          formatter: '{d}%',
          position: "inside"
        },
        // startAngle:-5,
        data: [{
            value: value2 || 0,
            name: "已提现"
          }, {
            value: value1 || 0,
            name: "未提现"
          }

        ]
      }]
    })
  },
  // 拒绝提现
  shopStaffFail() {
    const that=this
    wx.showModal({
      title: '确定拒绝',
      confirmText:'拒绝',
      content: `${this.data.userInfo.nick}提现￥${this.data.userInfo.withdraw.money}`,
      success(res) {
        if (res.confirm) {
          controllers.shopStaffFail({
            sessionId: wx.getStorageSync('token'),
            shopId: wx.getStorageSync('shopId'),
            id: that.data.userInfo.withdraw.id
          }).then(() => {
            that.staffDetail()
            wx.showToast({
              title: '已拒绝提现',
            })
          })
        }
      }
    })
    
  },
  // 同意提现
  shopStaffSuccess() {
    const that=this
    wx.showModal({
      title: '确定同意',
      confirmText:'同意',
      content: `${this.data.userInfo.nick}提现￥${this.data.userInfo.withdraw.money}`,
      success(res) {
        if (res.confirm) {
          controllers.shopStaffSuccess({
            sessionId: wx.getStorageSync('token'),
            shopId: wx.getStorageSync('shopId'),
            id: that.data.userInfo.withdraw.id
          }).then(() => {
            that.staffDetail()
            wx.showToast({
              title: '已同意提现',
            })
          })
        }
      }
    })
    
  },


  // 切换栏目
  changeIndex(e) {
    const index = e.currentTarget.dataset.index
    this.setData({
      currentIndex: index
    })
    this.getOrderList()
  },
  // 获取订单列表
  getOrderList() {
    if (!this.data.getMore) {
      this.setData({
        orderList: [],
        pageNumber: 1
      })
    }
    let value = {
      sessionId: wx.getStorageSync('token'),
      shopId: wx.getStorageSync('shopId'),
      // accountId: wx.getStorageSync('accountId'),
      shopAccountId: this.data.shopAccountId,
      endTime: this.data.endTime,
      startTime: this.data.startTime,
      pageNumber: this.data.pageNumber,
      pageSize: 20,
    }
    let index = this.data.currentIndex
    switch (index) {
      case 0:
      case 3://员工订单列表(线上，云服务)
        value.type = index==0 ? 1 : 2
        controllers.staffOrderPage(value).then((res) => {
          this.handleOrderData(res.data)
        })
        break;
      case 1://线下订单
        controllers.selectOrder(value).then((res) => {
          this.handleOrderData(res.data)
        })
        break;
      case 2://线下预约
        controllers.shopPage(value).then((res) => {
          this.handleOrderData(res.data)
        })
        break;
      case 4://会员卡提成
        controllers.vipOrderPage(value).then((res) => {
          this.handleOrderData(res.data)
        }) 
        break;
      case 5://提成记录
        value.genre = 0,
        value.amountType = 0,
        value.accountId = wx.getStorageSync('accountId'),
        controllers.orderStaff(value).then((res) => {
          this.handleOrderData(res.data)
        })  
        break;
      case 6:// 提现记录
        controllers.shopStaffPage(value).then((res) => {
          this.handleOrderData(res.data)
        })
        break;
    }
  },

  // 数据处理
  handleOrderData(data) {
    const index = this.data.currentIndex
    const list = data.list
    list.forEach(item => {
      item.money = item.money ? item.money.toFixed(2) : '00.00'
      item.shopAccountReward = item.shopAccountReward ? item.shopAccountReward.toFixed(2) : '00.00'
      const state = item.state
      switch (index) {
        case 0:
        case 3:
          if (state == 4 || state == 5 || state == 6 || state == 10) {
            item.stateName = '已取消'
          } else if (state == 8 || state == 9) {
            item.stateName = '已完成'
            item.greenColor = true
          } else if (state == 12) {
            item.stateName = '待核销'
            item.orderFinish = true
          } else {
            item.stateName = '待处理'
          }
          break;
        case 1:
          if (state == 0) {
            item.stateName = '待处理'
          } else if (state == 1) {
            item.stateName = '已结算'
            item.greenColor = true
          } else {
            item.stateName = '已取消'
          }
          break;
        case 5:
          item.stateName = '已结算'
          item.greenColor = true
          if (item.lowLine) {
            item.typeName = '线下订单收入'
          } else {
            if (item.type == 1) {
              item.typeName = '线上订单收入'
            } else if (item.type == 7) {
              item.typeName = '云服务订单收入'
            }
          }
          break;
        case 6:
          if (state == 0) {
            item.stateName = '待处理'
          } else if (state == 1) {
            item.stateName = '提现失败'
          } else {
            item.greenColor = true
            item.stateName = '提现成功'
          }
          break;  
      }
    })
    const orderList = this.data.orderList
    orderList.push(...list)
    this.setData({
      orderList,
      lastPage: data.lastPage,
      getMore: false
    })

  },

  // 详情页
  toOrderDetails(e) {
    const index = e.currentTarget.dataset.index
    let item = this.data.orderList[index]
    const currentIndex = this.data.currentIndex
    switch (currentIndex) {
      case 0:
        wx.navigateTo({
          url: '/pages/order/productOrder-detail/productOrder-detail?id=' + item.orderNo + '&state=' + item.state
        })
        break;
      case 1:
        wx.navigateTo({
          url: '/pages/settlement/OrderDetails/OrderDetails?orderNo=' + item.orderNo,
        })
        break;
      case 2:
        wx.navigateTo({
          url: '/pages/order/appointment-recordDetail/appointment-recordDetail?id=' + item.id,
        })
        break;
      case 3:
        wx.navigateTo({
          url: '/pages/order/cloudOrder-detail/cloudOrder-detail?id=' + item.orderNo + '&state=' + item.state
        })
        break;
      case 5:
        if (item.lowLine) {
          wx.navigateTo({
            url: '/pages/settlement/OrderDetails/OrderDetails?orderNo=' + item.orderNo,
          })
        } else {
          if (item.type == 1) {
            wx.navigateTo({
              url: '/pages/order/productOrder-detail/productOrder-detail?id=' + item.orderNo + '&state=' + item.state
            })
          } else if (item.type == 7) {
            wx.navigateTo({
              url: '/pages/order/cloudOrder-detail/cloudOrder-detail?id=' + item.orderNo + '&state=' + item.state
            })
          }
        }
        break;
      case 6:
        let detail = {
          userInfo: this.data.userInfo,
          orderDetail: item
        }
        detail = JSON.stringify(detail)
        wx.navigateTo({
          url: '/pages-echarts/PersonnelDetails/commissionDetail/commissionDetail?detail=' + detail
        })
        break;
    }
  },

  // clikcTabs(e) {
  //   const   index   = e.currentTarget.dataset.index

  //   let tabs = this.data.tabs

  //   tabs.forEach((v, i) => i === index ? v.isActive = true : v.isActive = false);
  //   this.setData({
  //     tabs,
  //     status:index
  //   })
  //   if(index!=3)
  //    this.checkOrder()
  //    else
  //    this.commissionList()
  // },

  // checkOrder(id) {
  //   let that = this
  //   let status = 6;
  //   if (that.data.status == 0) {
  //     status = 6
  //   } else if (that.data.status == 1) {
  //     status = 1
  //   } else {
  //     status = 7
  //   }
  //   controllers.staffPage({
  //     sessionId: wx.getStorageSync('token'),
  //     shopId: wx.getStorageSync('shopId'),
  //     shopAccountId: id || that.data.shopAccountId,
  //     pageSize: 20,
  //     pageNumber: 1,
  //     type: status || 6,
  //     startTime: that.data.startTime,
  //     endTime: that.data.endTime

  //   }).then(res => {
  //     that.setData({
  //       orderList: res.data.list
  //     })
  //   })


  // },
  // commissionList(id) {
  //   let that = this
  //   controllers.commissionList({
  //     sessionId: wx.getStorageSync('token'),
  //     shopAccountId: id || that.data.shopAccountId,
  //   }).then(res => {

  //     //code	0出错1成功2请登录3需绑定手机号
  //     if (res.code == 1) {
  //       let list = res.data.history
  //       for (let i = 0; i < list.length; i++) {
  //         list[i].timeMonth = new Date(list[i].createTime).getMonth() + 1
  //       }
  //       that.setData({
  //         commissionList: res.data,
  //         history: list
  //       })
  //     }
  //   })
  // },
  // pDetails() {
  //   wx.navigateTo({
  //     url: '../Commission/CommissionDetalis?shopAccountId=' + this.data.shopAccountId
  //   })
  // },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    if (this.data.lastPage) return
    this.setData({
      pageNumber: this.data.pageNumber + 1,
      getMore: true
    })
    this.getOrderList()
  },


  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage: function () {

  // }

  //获取当前日期
  getNowTime() {
    let time = new Date()
    let endTime = new Date(time.getTime() + 30 * 24 * 3600 * 1000)
    console.log(time)
    console.log(endTime)
    let year = time.getFullYear()
    let endYear = endTime.getFullYear()
    let month = time.getMonth() + 1
    let endMonth = endTime.getMonth() + 1
    let day = time.getDate()
    let endDay = endTime.getDate()
    if (month < 10) {
      month = "0" + month
    }
    if (day < 10) {
      day = "0" + day
    }
    if (endMonth < 10) {
      endMonth = "0" + endMonth
    }
    if (endDay < 10) {
      endDay = "0" + endDay
    }
    this.setData({
      startTime: year + '-' + month + '-' + day,
      endTime: endYear + '-' + endMonth + '-' + endDay
    })
  },

  //改变开始时间
  bindStartChange(e) {
    this.setData({
      startTime: e.detail.value
    })
    this.getOrderList()
  },

  //改变结束时间
  bindEndChange(e) {
    this.setData({
      endTime: e.detail.value
    })
    this.getOrderList()
  },
  // 重置时间
  reset() {
    this.setData({
      endTime: '',
      startTime: ''
    })
    this.getOrderList()
  },

  //跳转员工编辑页
  toAddStaff() {
    wx.navigateTo({
      url: '/pages/userStatistics/AddPersonnel/AddPersonnel?staffDetail=' + encodeURIComponent(JSON.stringify(this.data.userInfo)),
    })
  },

  //结算
  settlementMoney(e) {
    let id = e.currentTarget.dataset.id
    let shopId = wx.getStorageSync('shopId')
    controllers.settlementMoney({
      commissionId: id,
      shopId: shopId
    }).then(res => {
      wx.showToast({
        icon: "none",
        title: '结算成功',
        duration: 1500
      })
      this.commissionList()
    })
  }
})